package com.bw.common.vm

import android.util.Log
import androidx.lifecycle.ViewModel
import com.bw.common.intent.BaseViewIntent
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.newSingleThreadContext
import java.util.concurrent.Executors

abstract class BaseViewModel<I : BaseViewIntent> : ViewModel() {

    val channel: Channel<I> = Channel(Channel.UNLIMITED)

    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        Log.e("ViewModel", "VideModel层发生异常：" + throwable.message)
    }

    //自定义协程作用域
    val mViewModelScope = CoroutineScope(Dispatchers.Main + SupervisorJob() + exceptionHandler)

    //自定义调度器
    val mSingleTreadDispatcher = newSingleThreadContext("SingleThreadDispatcher")
    val mFixedTreadDispatcher = newFixedThreadPoolContext(32, "FixedThreadDispatcher")

    //使用Executors创建线程池的方式来创建调度器
    val mDispatcher = Executors.newFixedThreadPool(16).asCoroutineDispatcher()

    init {
        mViewModelScope.launch {
            //使用receiveAsFlow()可接收相同值，consumeAsFlow()不可以
            channel.receiveAsFlow().collect {
                dispatchIntent(it)
            }
        }
    }

    abstract fun dispatchIntent(intent: I)

}